package com.ctz.commonframe.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.ctz.commonframe.entity.ImageItem;
import com.ctz.commonframe.ui.widget.FileChooseActivity;
import com.ctz.commonframe.ui.widget.ImageBucketChooseActivity;

import top.zibin.luban.Luban;

@SuppressLint("NewApi")
public class PickImageUtil {
	public static final int REQUEST_CODE_TAKE_PHOTO = 30001;
	public static final int REQUEST_CODE_SELECT_IMAGE = 30002;
	public static final int REQUEST_CODE_PICK_FILE = 30003;

	private static PickImageUtil instance;

	private Activity activity;
	private OnPickImageResultListener listener;
	private String takePhotoPath;

	public interface OnPickImageResultListener {
		void onResult(List<ImageItem> imageList);
	}

	private PickImageUtil() {}

	public synchronized static PickImageUtil getInstance() {
		if (instance == null)
			instance = new PickImageUtil();
		return instance;
	}

	public void takePhoto(Activity activity, OnPickImageResultListener listener) {
		this.activity = activity;
		this.listener = listener;
		takePhotoPath = FilePathUtil.getImageDir(activity) + File.separator + FilePathUtil.getImageFileName(System.currentTimeMillis());
		File file = new File(takePhotoPath);
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		Uri photoUri = null;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			photoUri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", file);
		} else {
			photoUri = Uri.fromFile(file);
		}
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		activity.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
	}

	public void selectImage(Activity activity, OnPickImageResultListener listener) {
		this.activity = activity;
		this.listener = listener;
//		Intent intentImage = new Intent(activity, ImageBucketChooseActivity.class);
//		activity.startActivityForResult(intentImage, REQUEST_CODE_SELECT_IMAGE);

		Intent intentImage = new Intent(Intent.ACTION_PICK);
		intentImage.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		activity.startActivityForResult(intentImage, REQUEST_CODE_SELECT_IMAGE);
	}

	public void pickFile(Activity activity, OnPickImageResultListener listener){
		this.activity = activity;
		this.listener = listener;
		Intent intent = new Intent(activity, FileChooseActivity.class);
        activity.startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
	}

	public void handleActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == Activity.RESULT_OK){
			switch (requestCode) {
                case REQUEST_CODE_TAKE_PHOTO:
                    ImageItem item = compressPhoto(activity, takePhotoPath);
                    List<ImageItem> list = null;
                    if(item != null){
                        list = new ArrayList<>();
                        list.add(item);
                    }
                    listener.onResult(list);
                    break;
                case REQUEST_CODE_SELECT_IMAGE:
//                    List<ImageItem> selectedList = (List<ImageItem>) data.getSerializableExtra(ImageBucketChooseActivity.KEY_SELECTED_IMAGES);
//                    List<ImageItem> compressedList = new ArrayList<>();
//                    for (ImageItem oldItem: selectedList){
//                        ImageItem newItem = compressPhoto(activity, oldItem.imagePath);
//                        compressedList.add(newItem);
//                    }
					if (data.getData() != null) {
						ImageItem newItem = handleImageUri(activity, data.getData());
						if (newItem != null) {
							List<ImageItem> resultList = new ArrayList<>();
							resultList.add(newItem);
							listener.onResult(resultList);
						}
					}
                    break;
                case REQUEST_CODE_PICK_FILE:
                    ImageItem fileItem = (ImageItem) data.getSerializableExtra("file_data");
                    List<ImageItem> fileList = null;
                    if(fileItem != null){
                        fileList = new ArrayList<>();
                        fileList.add(fileItem);
                    }
                    listener.onResult(fileList);
                    break;

			}
		}
	}

	private ImageItem handleImageUri(Context context, Uri uri) {
		String path = ImagePathUtil.getRealPathFromUri(context, uri);
		if (TextUtils.isEmpty(path))
			return null;
		ImageItem item = compressPhoto(activity, path);
		return item;
	}
	
	private static ImageItem compressPhoto(Context context, String sourcePath) {
		try {
			File file = Luban.with(context).get(sourcePath);
			ImageItem item = new ImageItem();
			item.imageName = file.getName();
			item.size = String.valueOf(file.length());
			item.imagePath = file.getAbsolutePath();
			return item;
		} catch (IOException e) {
			e.printStackTrace();
		}


//		final float scale = context.getResources().getDisplayMetrics().density;
//		int destSize = (int) (80 * scale + 0.5f);
//		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
//		bmOptions.inJustDecodeBounds = true;
//		BitmapFactory.decodeFile(sourcePath, bmOptions);
//		int photoW = bmOptions.outWidth;
//		int photoH = bmOptions.outHeight;
//		int scaleFactor = Math.min(photoW / destSize, photoH / destSize);
//		bmOptions.inJustDecodeBounds = false;
//		bmOptions.inSampleSize = scaleFactor;
//		Bitmap bitmap = BitmapFactory.decodeFile(sourcePath, bmOptions);
//		saveBitmap(bitmap, sourcePath);
//		if (saveBitmap(bitmap, sourcePath)) {
//			ImageItem item = new ImageItem();
//			item.imageName = new File(sourcePath).getName();
//			item.size = String.valueOf(new File(sourcePath).length());
//			item.imagePath = sourcePath;
//			return item;
//		}
//
		return null;
	}

	private static boolean saveBitmap(Bitmap bitmap, String savePath) {
		boolean result = false;
		File f = new File(savePath);
		FileOutputStream fOut;
		try {
            //noinspection ResultOfMethodCallIgnored
            f.delete();
			f.createNewFile();
			fOut = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
			fOut.flush();
			fOut.close();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
